package com.xca.znb.view;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.google.gson.Gson;
import com.xca.znb.R;
import com.xca.znb.model.impl.FeedbackImpl;
import com.xca.znb.presenter.FeedbackPresenter;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;


public class FeedbackActivity extends AppCompatActivity {

    private FeedbackPresenter presenter ;
    private static final int REQUEST_PICK_IMAGES = 88;
    private static final int PERMISSION_REQUEST_CODE = 666;
    private List<Uri> selectedImages = new ArrayList<>();
    private ImageAdapter adapter;

    private EditText FeedbackInput;
    private Button FeedbackSubmit;
    private ImageView FeedbackBack;
    private ImageButton addPhoto ;
    private GridView showPhoto ;

    @SuppressLint("WrongViewCast")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//      getWindow().setEnterTransition(new Slide());    // 从下往上滑动效果
        setContentView(R.layout.activity_test_feedback);
        FeedbackBack=findViewById(R.id.feedback_back);

        FeedbackInput = findViewById(R.id.feedback_input);
        FeedbackSubmit = findViewById(R.id.feedback_submit);
        addPhoto = findViewById(R.id.publish_feedback_addPhoto);
        showPhoto = findViewById(R.id.rv_feedback_photo);

        FeedbackImpl feedback = new FeedbackImpl(this) ;
        presenter = new FeedbackPresenter(feedback);

        adapter = new ImageAdapter();
        showPhoto.setAdapter(adapter);

        addPhoto.setOnClickListener(v -> pickImagesFromGallery());

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    PERMISSION_REQUEST_CODE);
        }


        FeedbackBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });


        FeedbackSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //获取输入内容
                String text = FeedbackInput.getText().toString() ;
                //获取图片列表
                String[] imgList = new String[selectedImages.size()];
                for (int i=0 ; i<imgList.length ; i++){
                    String img = String.valueOf(selectedImages.get(i)) ;
                    Uri uri = Uri.parse(img);
                    String img_l = saveImageToAppFolder(uri);
                    imgList[i] = img_l ;
                }
                Gson gson = new Gson() ;
                String jsonImages = gson.toJson(imgList);
                //获取发布者id
                SharedPreferences sharedPreferences = getSharedPreferences("loginPhone", Context.MODE_PRIVATE);
                String phone = sharedPreferences.getString("phone" , "");

                if (text.isEmpty()){
                    Toast.makeText(FeedbackActivity.this, "请输入内容", Toast.LENGTH_SHORT).show();
                    return;
                }

                boolean isAdd = presenter.addFeedback(text , jsonImages , phone) ;
                if (isAdd){
                    Toast.makeText(FeedbackActivity.this, "反馈成功", Toast.LENGTH_SHORT).show();
                    finish();
                }else {
                    Toast.makeText(FeedbackActivity.this, "提交失败", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
    private String saveImageToAppFolder(Uri imageUri) {
        String savedImagePath = null;

        if (imageUri == null || imageUri.toString().isEmpty()) {
            Log.e("ImageSave", "Invalid image Uri provided");
            return null;
        }

        try {
            File dir_news = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
            if (dir_news == null) {
                Log.e("ImageSave", "Failed to get app's private directory");
                return null;
            }

            if (!dir_news.exists() && !dir_news.mkdirs()) {
                Log.e("ImageSave", "Failed to create directories");
                return null;
            }

            // 新增逻辑：确保文件名唯一
            String imageNameBase = "image_";
            String imageNameExtension = ".jpg";
            File file;
            int counter = 0;
            do {
                String imageName = imageNameBase + System.currentTimeMillis() + (counter > 0 ? "_" + counter : "") + imageNameExtension;
                file = new File(dir_news, imageName);
                counter++;
            } while (file.exists());

            try (InputStream inputStream = getContentResolver().openInputStream(imageUri);
                 FileOutputStream outputStream = new FileOutputStream(file)) {

                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }

                savedImagePath = file.getAbsolutePath();
                Log.d("ImageSave", "Image saved successfully at: " + savedImagePath);
            }
        } catch (SecurityException se) {
            Log.e("ImageSave", "Security exception when accessing storage", se);
        } catch (FileNotFoundException fnfe) {
            Log.e("ImageSave", "Image file not found", fnfe);
        } catch (IOException ioe) {
            Log.e("ImageSave", "Error occurred during image saving", ioe);
        }

        return savedImagePath;
    }


    //将图片列表路径转化为JSON格式
    private String uriListToJson(List<Uri> uriList) {
        Gson gson = new Gson();
        return gson.toJson(uriList);
    }

    private void pickImagesFromGallery() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType("image/*");
        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); // 允许选择多张图片
        startActivityForResult(intent, REQUEST_PICK_IMAGES);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 用户已授权，可以进行图片选择
            } else {
                //Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_PICK_IMAGES && resultCode == RESULT_OK) {
            if (data.getClipData() != null) {
                int count = data.getClipData().getItemCount();
                for (int i = 0; i < count; i++) {
                    Uri imageUri = data.getClipData().getItemAt(i).getUri();
                    selectedImages.add(imageUri);
                }
            } else if (data.getData() != null) {
                Uri imageUri = data.getData();
                selectedImages.add(imageUri);
            }
            adapter.notifyDataSetChanged();
        }
    }

    private class ImageAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return selectedImages.size();
        }

        @Override
        public Object getItem(int position) {
            return selectedImages.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.goods_photo_item, parent, false);
                holder = new ViewHolder();
                holder.imageView = convertView.findViewById(R.id.goods_photo);
                holder.closeImageView = convertView.findViewById(R.id.delete_photo);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            Uri imageUri = selectedImages.get(position);
            holder.imageView.setImageURI(imageUri);
            holder.closeImageView.setVisibility(View.VISIBLE);

            // 在这里直接设置关闭按钮的点击监听器
            holder.closeImageView.setOnClickListener(v -> {
                if (selectedImages.size() > position) { // 确保索引有效
                    selectedImages.remove(position);
                    adapter.notifyDataSetChanged();
                }
            });

            return convertView;
        }

        private class ViewHolder {
            ImageView imageView;
            ImageView closeImageView;
        }
    }
}
